package com.meitianhui.convenitenbuy.module.mine.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.mine.adapter.ConsumerAddressAdapter;
import com.meitianhui.convenitenbuy.module.mine.contract.ReceivingAddressContract;
import com.meitianhui.convenitenbuy.module.mine.di.DaggerMineComponent;
import com.meitianhui.convenitenbuy.module.mine.di.MineModule;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerAddress;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.AddressDefaultEventBean;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.AddressEventBean;
import com.meitianhui.convenitenbuy.module.mine.presenter.ReceivingAddressPresenter;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.swipemenulistview.SwipeMenu;
import com.meitianhui.convenitenbuy.widget.swipemenulistview.SwipeMenuCreator;
import com.meitianhui.convenitenbuy.widget.swipemenulistview.SwipeMenuItem;
import com.meitianhui.convenitenbuy.widget.swipemenulistview.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 *  Created by amy on 2017/11/13.
 */

public class ReceivingAddressActivity extends BaseToolbarActivity implements ReceivingAddressContract.View {

    @Inject
    ReceivingAddressPresenter mReceivingAddressPresenter;
    private SwipeMenuListView mRvReceivingAddress;
    private LinearLayout mLlReceivingNone;
    private Button mBtnReceivingIncrease;
    List<ConsumerAddress.ConsumerData> consumerAddressList = new ArrayList<>();//地址列表
    private ConsumerAddressAdapter mConsumerAddressAdapter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setTbTitle("收货地址");
        isEnable(false);
        initId();
        initAdapter();
        DaggerMineComponent.builder().mineModule(new MineModule(this)).appComponent(App.getInstance().getAppComponent()).build().inject(this);
        showUserAddressLocal();
        getUserAddressInfo();
    }

    private void showUserAddressLocal() {
        //先设置本地的数据，再获取网络数据
        if (InfoProvider.getUserReceivingAddress(this) == null){
            return;
        }
        mConsumerAddressAdapter.setData(InfoProvider.getUserReceivingAddress(this));
    }

    private void initAdapter() {
        mConsumerAddressAdapter = new ConsumerAddressAdapter(this, consumerAddressList);
        mRvReceivingAddress.setAdapter(mConsumerAddressAdapter);
        //设置侧滑菜单
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                deleteItem.setWidth((int) getResources().getDimension(R.dimen.dp_72));
                deleteItem.setTitle("删除地址");
                deleteItem.setTitleSize(18);
                deleteItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(deleteItem);
            }
        };
        mRvReceivingAddress.setMenuCreator(creator);
        //条目点击事件
        mRvReceivingAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(consumerAddressList.size()<=0){
                    return;
                }
                //跳转到信息修改页面
                Intent intent = new Intent(ReceivingAddressActivity.this, AddOrNotifyAddressActivity.class);
                intent.putExtra(JumpUtil.JUMP_ADDRESS_CHANGE, 1);
                intent.putExtra("data", consumerAddressList.get(position));
               if (consumerAddressList.get(position).getIs_major_addr().equals("Y")){
                   intent.putExtra("isMajor",true);
               }
               //consumerAddressList.remove(position);
                startActivity(intent);
            }
        });

        //滑动删除
        mRvReceivingAddress.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                if(consumerAddressList.size()>0){
                String address_id = consumerAddressList.get(position).getAddress_id();
                consumerAddressList.remove(position);
                if (consumerAddressList.size() == 0) {
                    mLlReceivingNone.setVisibility(View.VISIBLE);
                    mRvReceivingAddress.setVisibility(View.GONE);
                    RxBus.get().post(new AddressDefaultEventBean(""));
                }
                mConsumerAddressAdapter.setData(consumerAddressList);
                mReceivingAddressPresenter.deleteReceivingAddress(address_id);
                //保存到本地
                PreferenceUtils.saveObject(ReceivingAddressActivity.this,Constants.USER_RECEIVING_ADDRESS,consumerAddressList);
                }
                return false;
            }
        });

        Disposable disposable = RxBus.get().toFlowable(AddressEventBean.class).subscribe(new Consumer<AddressEventBean>() {
            @Override
            public void accept(AddressEventBean addressEventBean) throws Exception {
                if (addressEventBean.type == Constants.ADDRESS_NOTIFY_RA_ACTIVITY) {

                    mReceivingAddressPresenter.getUserAddressInfo();
                } else {
                    //处理条目点击事件
                    if (consumerAddressList != null && consumerAddressList.get(addressEventBean.type).getIs_major_addr().equals("N")) {
                        for (int i = 0; i < consumerAddressList.size(); i++) {
                            if (i == addressEventBean.type) {
                                consumerAddressList.get(i).setIs_major_addr("Y");
                            } else {
                                consumerAddressList.get(i).setIs_major_addr("N");
                            }
                        }
                        mConsumerAddressAdapter.setData(consumerAddressList);
                        //保存到本地
                        PreferenceUtils.saveObject(ReceivingAddressActivity.this,Constants.USER_RECEIVING_ADDRESS,consumerAddressList);
                        mReceivingAddressPresenter.notifyUserMajorAddress(consumerAddressList.get(addressEventBean.type));
                    }
                }
            }
        });

        mCompositeDisposable.add(disposable);
    }




    private void initId() {
        mRvReceivingAddress = getViewById(R.id.rv_receiving_address);
        mLlReceivingNone = getViewById(R.id.ll_receiving_none);
        mBtnReceivingIncrease = getViewById(R.id.btn_receiving_increase);
        //初始化Rxjava的仿手抖
        RxUtils.bindEvents(mBtnReceivingIncrease, this);
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.btn_receiving_increase:
                //跳转到增加地址界面
                Intent intent = new Intent(this, AddOrNotifyAddressActivity.class);
                intent.putExtra(JumpUtil.JUMP_ADDRESS_CHANGE, 0);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_receiving_address;
    }

    @Override
    protected void onRefreshData() {

    }

    public void getUserAddressInfo() {
        mReceivingAddressPresenter.getUserAddressInfo();

    }

    @Override
    public void showError(String msg) {
        TipUtils.showToast(App.getInstance(),msg);
    }

    @Override
    public void showDataNone() {
        mLlReceivingNone.setVisibility(View.VISIBLE);

    }

    @Override
    public void showAddress(List<ConsumerAddress.ConsumerData> consumerDatas) {
        mLlReceivingNone.setVisibility(View.GONE);
        mRvReceivingAddress.setVisibility(View.VISIBLE);
        consumerAddressList = consumerDatas;
        mConsumerAddressAdapter.setData(consumerDatas);

    }

    @Override
    public void delSucc() {
        TipUtils.showToast(App.getInstance(),"删除成功");
    }

    @Override
    public void updateDefaultSucc() {
        TipUtils.showToast(App.getInstance(),"修改默认地址成功");

    }

}
